// data-handler.js - 数据处理和页面更新模块

// 更新销售分析页面的数据
function updateSalesData(data) {
    if (!data) return;
    
    console.log('更新销售数据:', data);
    
    // 更新销售总额
    document.getElementById('totalSales').textContent = `¥${formatNumber(data.totalSales)}`;
    document.querySelector('#salesTab .grid-item-1 .stat-label').textContent = 
        `与昨日相比 ${data.salesGrowth > 0 ? '+' : ''}${data.salesGrowth}%`;
    
    // 更新订单总数
    document.getElementById('totalOrders').textContent = formatNumber(data.totalOrders);
    document.querySelector('#salesTab .grid-item-2 .stat-label').textContent = 
        `与昨日相比 ${data.ordersGrowth > 0 ? '+' : ''}${data.ordersGrowth}%`;
    
    // 更新客流量
    document.getElementById('customerCount').textContent = formatNumber(data.customerCount);
    document.querySelector('#salesTab .grid-item-3 .stat-label').textContent = 
        `与昨日相比 ${data.customerGrowth > 0 ? '+' : ''}${data.customerGrowth}%`;
    
    // 更新平均客单价
    document.getElementById('avgOrderValue').textContent = `¥${data.avgOrderValue.toFixed(2)}`;
    document.querySelector('#salesTab .grid-item-4 .stat-label').textContent = 
        `较上周 ${data.avgOrderGrowth > 0 ? '+' : ''}${data.avgOrderGrowth}%`;
    
    // 更新库存预警
    updateInventoryAlerts(data.inventoryAlerts);
    
    // 更新实时销售
    updateRealTimeSales(data.realTimeSales);
}

// 更新库存预警列表
function updateInventoryAlerts(alerts) {
    const container = document.querySelector('#salesTab .grid-item-7 .list-container ul');
    container.innerHTML = ''; // 清空现有内容
    
    alerts.forEach(item => {
        const li = document.createElement('li');
        li.textContent = `${item.product} (库存: ${item.stock})`;
        container.appendChild(li);
    });
}

// 更新实时销售列表
function updateRealTimeSales(sales) {
    const container = document.querySelector('#salesTab .grid-item-9 .list-container');
    container.innerHTML = ''; // 清空现有内容
    
    sales.forEach(sale => {
        const div = document.createElement('div');
        div.style.padding = '8px 0';
        div.style.borderBottom = '1px solid #2a5a8c';
        div.textContent = `[${sale.time}] 订单 ${sale.orderNo} - ¥${sale.amount}`;
        container.appendChild(div);
    });
}

// 更新销售分析图表
function updateSalesCharts(data) {
    if (!data) return;
    
    // 更新热销商品分类图表
    updateCategoryChart(data.hotCategories);
    
    // 更新销售趋势图表
    updateTrendChart(data.weeklyTrend);
    
    // 更新促销活动效果图表
    updatePromotionChart(data.promotionEffects);
}

// 更新热销商品分类图表
function updateCategoryChart(categories) {
    if (!chartInstances['categoryChart']) return;
    
    const chart = chartInstances['categoryChart'].chart;
    chart.data.labels = categories.map(item => item.name);
    chart.data.datasets[0].data = categories.map(item => item.value);
    chart.update();
}

// 更新销售趋势图表
function updateTrendChart(weeklyTrend) {
    console.log('更新销售趋势图表，数据:', weeklyTrend);
    
    if (!chartInstances['trendChart']) {
        console.error('销售趋势图表实例不存在');
        return;
    }
    
    const chart = chartInstances['trendChart'].chart;
    chart.data.labels = weeklyTrend.map(item => item.day);
    chart.data.datasets[0].data = weeklyTrend.map(item => item.sales);
    chart.update();
    console.log('销售趋势图表更新完成');
}

// 更新促销活动效果图表
function updatePromotionChart(promotionEffects) {
    console.log('更新促销活动图表，数据:', promotionEffects);
    
    if (!chartInstances['promotionChart']) {
        console.error('促销活动图表实例不存在');
        return;
    }
    
    const chart = chartInstances['promotionChart'].chart;
    chart.data.labels = promotionEffects.map(item => item.activity);
    chart.data.datasets[0].data = promotionEffects.map(item => item.increase);
    chart.update();
    console.log('促销活动图表更新完成');
}



//如下是会员分析页面相关函数
// 更新会员分析页面的数据
function updateMemberData(data) {
    if (!data) return;
    
    console.log('更新会员数据:', data);
    
    // 更新会员总数
    document.getElementById('memberTotal').textContent = formatNumber(data.memberTotal);
    document.querySelector('#memberTab .grid-item-1 .stat-label').textContent = 
        `本月新增 ${data.newMembersThisMonth} 人`;
    
    // 更新活跃会员数
    document.getElementById('activeMembers').textContent = formatNumber(data.activeMembers);
    document.querySelector('#memberTab .grid-item-2 .stat-label').textContent = 
        `活跃率 ${data.activeRate}%`;
    
    // 更新会员平均消费
    document.getElementById('avgMemberSpending').textContent = `¥${data.avgMemberSpending.toFixed(2)}`;
    document.querySelector('#memberTab .grid-item-3 .stat-label').textContent = 
        `高于非会员 ${data.spendingComparison}%`;
    
    // 更新会员复购率
    document.getElementById('repurchaseRate').textContent = `${data.repurchaseRate}%`;
    document.querySelector('#memberTab .grid-item-4 .stat-label').textContent = 
        `较上月 ${data.repurchaseGrowth > 0 ? '+' : ''}${data.repurchaseGrowth}%`;
    
    // 更新高价值会员列表
    updateTopVipMembers(data.topVipMembers);
}

// 更新高价值会员列表
function updateTopVipMembers(topVipMembers) {
    const container = document.querySelector('#memberTab .grid-item-7 .list-container ul');
    container.innerHTML = ''; // 清空现有内容
    
    topVipMembers.forEach(member => {
        const li = document.createElement('li');
        li.textContent = `${member.vipId} - ${member.name} - 累计消费 ¥${formatNumber(member.totalSpending)}`;
        container.appendChild(li);
    });
}





// 更新商店分析页面的数据
function updateStoreData(data) {
    if (!data) return;
    
    console.log('更新商店数据:', data);
    
    // 更新门店总数
    document.getElementById('storeCount').textContent = data.storeCount;
    document.querySelector('#storeTab .grid-item-1 .stat-label').textContent = 
        `覆盖 ${data.coveredCities} 个城市`;
    
    // 更新营业中门店
    document.getElementById('operatingStores').textContent = data.operatingStores;
    document.querySelector('#storeTab .grid-item-2 .stat-label').textContent = 
        `${data.maintenanceStores} 家门店维护中`;
    
    // 更新今日总客流
    document.getElementById('overallTraffic').textContent = formatNumber(data.overallTraffic);
    document.querySelector('#storeTab .grid-item-3 .stat-label').textContent = 
        `较昨日 ${data.trafficGrowth > 0 ? '+' : ''}${data.trafficGrowth}%`;
    
    // 更新门店平均销售额
    document.getElementById('avgStoreSales').textContent = `¥${formatNumber(data.avgStoreSales)}`;
    document.querySelector('#storeTab .grid-item-4 .stat-label').textContent = 
        `较上月 ${data.avgSalesGrowth > 0 ? '+' : ''}${data.avgSalesGrowth}%`;
    
    // 更新低效门店列表
    updateLowEfficiencyStores(data.lowEfficiencyStores);
}

// 更新低效门店列表
function updateLowEfficiencyStores(lowEfficiencyStores) {
    const container = document.querySelector('#storeTab .grid-item-7 .list-container ul');
    container.innerHTML = ''; // 清空现有内容
    
    lowEfficiencyStores.forEach(store => {
        const li = document.createElement('li');
        li.textContent = `${store.store} - 日均销售额 ¥${formatNumber(store.dailySales)}`;
        container.appendChild(li);
    });
}









// 格式化数字（添加千位分隔符）
function formatNumber(num) {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

// 创建全局对象
window.dataHandler = {
    updateSalesData,
    updateInventoryAlerts,
    updateRealTimeSales,
    updateSalesCharts,
    updateCategoryChart,
    updateTrendChart,
    updatePromotionChart,
    updateMemberData,
    updateTopVipMembers,
    updateStoreData,
    updateLowEfficiencyStores
};